package org.nightknight.satobee.core;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class Server extends Thread {
    
    private static Contact me;
    
    public static Contact getMe() {
        return me;
    }
    
    static {
        try {
            me = new Contact(InetAddress.getLocalHost());
        } catch (UnknownHostException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private ServerSocket server;
    private List<IConRecListener> listeners = new ArrayList<IConRecListener>();

    // since it is abstract, no need to be protected
    public Server() {
    }
    
    @Override
    public void run() {
        try {
            server = new ServerSocket(0x2007);
            
            while (true) {
                Socket incoming = server.accept();
                fireConvRecListeners(incoming);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    public void addConvRecListener(IConRecListener listner) {
        this.listeners.add(listner);
    }

    public boolean removeConvRecListener(IConRecListener listener) {
        return this.listeners.remove(listener);
    }

    public void fireConvRecListeners(Socket s) {
        for (IConRecListener listener : listeners) {
            listener.convRecListener(s);
        }
    }
}
